package org.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.TypeUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.*;
import org.springframework.core.convert.ConversionService;

import javax.naming.Context;
import javax.naming.Name;
import javax.sound.sampled.Port;
import java.lang.reflect.Method;
import java.util.Hashtable;

/**
 * @Name AbstractAutowireCapableBeanFactory
 * @Description: 支持注入能力的 Bean 容器 [抽象] 类
 * 描述信息：该类继承自 AbstractBeanFactory，同时实现了 AutowireCapableBeanFactory 标识接口，具备二者的能力。
 * 说明：实现了创建 Bean 实例的接口，同时具备注入能力。
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-03-14 14:55:11
 **/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition) throws BeansException {
        Object proxyBean = resolveBeforeInstantiation(beanName, beanDefinition);
        if (proxyBean != null) return proxyBean;
        return doCreateBean(beanName, beanDefinition);
    }

    protected Object resolveBeforeInstantiation(String beanName, BeanDefinition beanDefinition) {
        Object proxyBean = applyBeanPostProcessorsBeforeInstantiation(beanDefinition.getBeanClass(), beanName);
        if (proxyBean != null) {
            proxyBean = applyBeanPostProcessorsAfterInitialization(beanDefinition.getBeanClass(), beanName);
        }
        return proxyBean;
    }

    protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) {
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                Object result = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessBeforeInstantiation(beanClass, beanName);
                if (result != null) return result;
            }
        }
        return null;
    }

    protected Object doCreateBean(String beanName, BeanDefinition beanDefinition) {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefinition);
            // 为解决循环依赖问题，当 Bean 实例化之后立即放入二级缓存 earlySingletonObjects 中，提前暴露引用，然后再设置属性
            if (beanDefinition.isSingleton()) {
                Object finalBean = bean;
                addSingletonFactory(beanName, new ObjectFactory<Object>() {
                    @Override
                    public Object getObject() throws BeansException {
                        // 提前返回二级缓存 earlySingletonObjects 中的 Bean 实例的引用
                        return getEarlyBeanReference(beanName, beanDefinition, finalBean);
                    }
                });
            }
            boolean continueWithPropertyPopulation = applyBeanPostProcessorsAfterInstantiation(beanName, bean);
            if (!continueWithPropertyPopulation) return bean;
            // 在设置 Bean 属性之前，允许 BeanPostProcessor 修改属性值
            applyBeanPostProcessorsBeforeApplyingPropertyValues(beanName, bean, beanDefinition);
            // 为 Bean 填充属性
            applyPropertyValues(beanName, bean, beanDefinition);
            // 执行 Bean 的初始化方法和 BeanPostProcessor 的前置和后置处理方法
            bean = initializeBean(beanName, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("实例化 Bean [" + beanDefinition.getBeanClass().getName() + "] 失败", e);
        }
        // 注册带有销毁方法的 Bean
        registerDisposableBeanIfNecessary(beanName, bean, beanDefinition);

        // 将代理 Bean 实例放进一级缓存 singletonObjects
        Object exposedObject = bean;
        if (beanDefinition.isSingleton()) {
            // 如果有代理对象，此处获取代理对象
            exposedObject = getSingleton(beanName);
            addSingleton(beanName, exposedObject);
        }
        return exposedObject;
    }

    /**
     * 获取二级缓存 earlySingletonObjects 中的 Bean 实例的引用
     *
     * @param beanName       Bean 名称
     * @param beanDefinition Bean 元信息
     * @param bean           Bean 实例
     * @return java.lang.Object Bean 实例的引用
     * @version v1.0.0
     * @author lichao
     * @date 2024-04-12 15:07:08
     */
    protected Object getEarlyBeanReference(String beanName, BeanDefinition beanDefinition, Object bean) {
        Object exposedObject = bean;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                exposedObject = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).getEarlyBeanReference(exposedObject, beanName);
                if (exposedObject == null) return null;
            }
        }
        return exposedObject;
    }

    /**
     * 在 Bean 实例化之后执行该方法（Bean 实例化之后的处理逻辑）
     * 如果返回 false（postProcessAfterInstantiation() 方法返回 true），直接返回 Bean 实例，则不再执行后续的设置属性操作。
     *
     * @param beanName Bean 名称
     * @param bean     Bean 实例
     * @return boolean 判断结果
     * @version v1.0.0
     * @author lichao
     * @date 2024-04-12 14:26:59
     */
    private boolean applyBeanPostProcessorsAfterInstantiation(String beanName, Object bean) {
        boolean continueWithPropertyPopulation = true;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                if (!((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessAfterInstantiation(bean, beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
        return continueWithPropertyPopulation;
    }

    /**
     * 在设置 Bean 属性之前，允许 BeanPostProcessor 修改属性值
     *
     * @param beanName       Bean 名称
     * @param bean           Bean 实例
     * @param beanDefinition Bean 元数据信息
     * @version v1.0.0
     * @author lichao
     * @date 2024-04-10 15:54:17
     */
    protected void applyBeanPostProcessorsBeforeApplyingPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                PropertyValues pvs = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessPropertyValues(beanDefinition.getPropertyValues(), bean, beanName);
                if (pvs != null) {
                    for (PropertyValue propertyValue : pvs.getPropertyValues()) {
                        beanDefinition.getPropertyValues().addPropertyValue(propertyValue);
                    }
                }
            }
        }
    }

    /**
     * 实例化 Bean
     *
     * @param beanDefinition Bean 定义信息
     * @return java.lang.Object Bean 实例
     * @version v1.0.0
     * @author lichao
     * @date 2024-03-15 14:18:00
     */
    protected Object createBeanInstance(BeanDefinition beanDefinition) {
        return getInstantiationStrategy().instantiate(beanDefinition);
    }

    /**
     * 为 Bean 实例填充属性
     *
     * @param beanName       Bean 实例名称
     * @param beanDefinition Bean 定义信息
     * @version v1.0.0
     * @author lichao
     * @date 2024-03-15 14:18:23
     */
    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            for (PropertyValue propertyValue : beanDefinition.getPropertyValues().getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                if (value instanceof BeanReference) {
                    // BeanA 依赖 BeanB，先实例化并引入 BeanB
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                } else {
                    // 类型转换
                    Class<?> sourceType = value.getClass();
                    Class<?> targetType = (Class<?>) TypeUtil.getFieldType(bean.getClass(), name);
                    ConversionService conversionService = getConversionService();
                    if (conversionService != null) {
                        if (conversionService.canConvert(sourceType, targetType)) {
                            value = conversionService.convert(value, targetType);
                        }
                    }
                }
                // 通过反射设置属性
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeansException("设置 Bean [" + beanDefinition.getBeanClass().getName() + "] 属性失败", e);
        }
    }

    protected Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) {
        // 为 Bean 实例绑定其所属的 BeanFactory 容器
        if (bean instanceof BeanFactoryAware) {
            ((BeanFactoryAware) bean).setBeanFactory(this);
        }
        // 执行 BeanPostProcessor 的前置处理
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);
        // 执行 Bean 的初始化方法
        try {
            invokeInitMethods(beanName, wrappedBean, beanDefinition);
        } catch (Throwable ex) {
            throw new BeansException(beanName + " --> 执行 Bean 的初始化方法失败!", ex);
        }
        // 执行 BeanPostProcessor 的后置处理
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        return wrappedBean;
    }

    /**
     * 执行 BeanPostProcessor 的前置处理
     *
     * @param bean     Bean 实例
     * @param beanName Bean 名称
     * @return java.lang.Object 结果
     * @version v1.0.0
     * @author lichao
     * @date 2024-03-19 17:26:44
     */
    protected Object applyBeanPostProcessorsBeforeInitialization(Object bean, String beanName) {
        Object result = bean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (current == null) return result;
            result = current;
        }
        return result;
    }

    /**
     * 执行 Bean 的初始化方法
     *
     * @param beanName       Bean 名称
     * @param wrappedBean    执行 BeanPostProcessor 的前置处理后的 Bean 实例
     * @param beanDefinition BeanDefinition 信息
     * @version v1.0.0
     * @author lichao
     * @date 2024-03-19 17:27:18
     */
    protected void invokeInitMethods(String beanName, Object wrappedBean, BeanDefinition beanDefinition) throws Throwable {
        // 1. 执行实现了 InitializingBean 接口的初始化方法
        if (wrappedBean instanceof InitializingBean) {
            ((InitializingBean) wrappedBean).afterPropertiesSet();
        }
        // 2. 执行在 Xml 配置文件中制定了 Bean 自定义的初始化方法
        // 条件: 避免同时继承自 InitializingBean，且自定义方法与 InitializingBean 方法同名，初始化方法执行两次的情况
        // 即: 既实现了 InitializingBean 接口, 又同时在 Xml 配置文件中指定了该初始化方法的情况
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName) && !(wrappedBean instanceof InitializingBean && "afterPropertiesSet".equals(initMethodName))) {
            Method initMethod = ClassUtil.getPublicMethod(beanDefinition.getBeanClass(), initMethodName);
            if (initMethod == null)
                throw new BeansException("Bean [" + beanName + "] 中没有发现名称为 '" + initMethodName + "' 的初始化方法");
            initMethod.invoke(wrappedBean);
        }
    }

    /**
     * 执行 BeanPostProcessor 的后置处理
     *
     * @param bean     Bean 实例
     * @param beanName Bean 名称
     * @return java.lang.Object 结果
     * @version v1.0.0
     * @author lichao
     * @date 2024-03-19 17:26:44
     */
    protected Object applyBeanPostProcessorsAfterInitialization(Object bean, String beanName) {
        Object result = bean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (current == null) return result;
            result = current;
        }
        return result;
    }

    /**
     * 注册带有销毁方法的单例 Bean, 即 Bean 继承自 DisposableBean 接口或有自定义的销毁方法, 且 scope == singleton 单例
     *
     * @param beanName       Bean 名称
     * @param bean           Bean 实例
     * @param beanDefinition BeanDefinition 信息
     * @version v1.0.0
     * @author lichao
     * @date 2024-03-20 15:13:05
     */
    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        // 只有单例 Bean 才会执行销毁方法
        if (beanDefinition.isSingleton()) {
            if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestoryMethodName())) {
                registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
            }
        }
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}

